<template>
  <ScrollContainer :style="spinStyle" v-if="ifEmpty">
    <a-collapse expandIconPosition="right" v-model:activeKey="activeKey">
      <a-collapse-panel
        v-for="item in list"
        :key="item.value"
        :header="item.label"
        v-show="item.ifShow"
        :forceRender="true"
        @click="select(item.value)"
      >
        <CollapseForm
          ref="formRef"
          :list="list"
          :type="item.value"
          :deletedList="deletedList"
          :currentSelect="currentSelect"
          :mode="props.mode"
          @select="selectChange"
        />
        <template #extra>
          <a-button
            @click.stop="handleDelete(item)"
            type="text"
            size="small"
            preIcon="ant-design:delete-filled"
          />
        </template>
      </a-collapse-panel>
    </a-collapse>
  </ScrollContainer>
  <h3 style="text-align: center; color: #00000061" v-else>请指定要导出的实体</h3>
  <div style="display: flex; justify-content: space-between; margin-top: 30px">
    <a-button type="primary" @click="handleShow">添加实体类型</a-button>
    <a-button type="primary" @click="handleDeleteAll">全部删除</a-button>
  </div>
</template>

<script lang="ts" setup>
  import { Collapse as ACollapse, CollapsePanel as ACollapsePanel } from 'ant-design-vue';
  import { ref, computed } from 'vue';
  import { ScrollContainer } from '/@/components/Container';
  import type { CSSProperties } from 'vue';
  import CollapseForm from './CollapseForm.vue';
  import { typeList } from './collapse.data';

  const props = defineProps({
    mode: {
      type: String,
    },
  });

  const emit = defineEmits(['success']);
  let activeKey = ref(['asset']);
  let list = ref(typeList);
  let currentSelect = ref();
  let deletedAllList = [
    'ASSET',
    'DEVICE',
    'ENTITY_VIEW',
    'DASHBOARD',
    'CUSTOMER',
    'DEVICE_PROFILE',
    'ASSET_PROFILE',
    'RULE_CHAIN',
    'WIDGETS_BUNDLE',
    'WIDGETS_BUNDLE',
    'NOTIFICATION_TEMPLATE',
    'NOTIFICATION_TARGET',
    'NOTIFICATION_RULE',
  ];
  let deletedList = ref<String[]>([]);
  let selectIndex = 0;
  const formRef = ref();

  const handleDelete = (item?: any, currentSelect?: String) => {
    if (currentSelect) {
      deletedList.value.push(currentSelect);
      deletedList.value = deletedAllList.filter((ele) => {
        return deletedList.value.includes(ele);
      });
      list.value = list.value.filter((ele, index) => {
        ele.value == currentSelect ? (selectIndex = index) : '';
        return ele.value != currentSelect;
      });
      formRef.value.forEach((item) => item.changeList());
    } else {
      deletedList.value.push(item.value);
      deletedList.value = deletedAllList.filter((ele) => {
        return deletedList.value.includes(ele);
      });
      list.value = list.value.filter((ele) => {
        return ele.value != item.value;
      });
      formRef.value.forEach((item) => item.changeList());
    }
  };

  const handleShow = (isSelect?: Boolean, changeSelect?: String) => {
    if (isSelect && changeSelect) {
      deletedList.value = deletedList.value.filter((item) => {
        return item != changeSelect;
      });
      deletedList.value = deletedAllList.filter((ele) => {
        return deletedList.value.includes(ele);
      });
      formRef.value.forEach((item) => item.changeList(true, deletedList.value));
      // selectIndex=1， 删了device
      typeList.some((item) => {
        item.value == changeSelect ? list.value.splice(selectIndex, 0, item) : '';
        return item.value == changeSelect;
      });
    } else {
      let obj = deletedList.value.shift();
      typeList.some((item) => {
        item.value == obj ? list.value.push(item) : '';
        return item.value == obj;
      });
    }
  };

  const handleDeleteAll = () => {
    list.value = [];
    deletedList.value = [];
    deletedList.value = [...deletedAllList];
  };

  const selectChange = (currentSelect, changeSelect) => {
    handleDelete('', currentSelect);
    handleShow(true, changeSelect);
  };
  const spinStyle = computed((): CSSProperties => {
    if (props.mode == 'add') {
      return {
        maxHeight: '230px',
      };
    } else {
      return {};
    }
  });
  const ifEmpty = computed((): Boolean => {
    return list.value.length == 0 ? false : true;
  });
  const select = (val) => (currentSelect.value = val);

  const close = () => {
    formRef.value.forEach((item) => item.resetFields());
    list.value = typeList;
  };

  const collectValues = async () => {
    let collapseFormValues = {};
    if (props.mode == 'add') {
      try {
        for (const item of formRef.value) {
          await item.validate();
          const values = item.getFieldsValue();
          Object.assign(collapseFormValues, {
            [values.type]: {
              allEntities: values.allEntity,
              entityIds: values.entityList ? [...values.entityList] : [],
              saveAttributes: values.exportProperties,
              saveCredentials: values.exportCredential,
              saveRelations: values.exportAssociations,
              syncStrategy: values.syncStrategy == 'default' ? null : values.syncStrategy,
            },
          });
        }
        emit('success', { collapseFormValues });
      } catch (error) {}
    } else if (props.mode == 'restore') {
      try {
        for (const item of formRef.value) {
          await item.validate();
          const values = item.getFieldsValue();
          Object.assign(collapseFormValues, {
            [values.type]: {
              findExistingEntityByName: values.findExistingEntityByName,
              loadAttributes: values.loadAttributes,
              loadCredentials: values.loadCredentials,
              loadRelations: values.loadRelations,
              removeOtherEntities: values.removeOtherEntities,
            },
          });
        }
        emit('success', { collapseFormValues });
      } catch (error) {}
    }
  };
  defineExpose({ close, collectValues });
</script>
